import store from '@/store'

function hasPermission(value, el = false) {
  if (!Array.isArray(value)) {
    throw new Error(`需要配置权限，例如v-permission="['getStatistics3,GET']"`)
  }

  // let a = [1,2,3,7], b = [1,2,3], 查看b数组中某个元素是否包含a数组中，并返回在该a数组中的索引
  const ruleNames = store.state.user.ruleNames
  const hasAuth = value.findIndex((v) => ruleNames.includes(v)) !== -1
  if (el && !hasAuth) {
    el.parentNode && el.parentNode.removeChild(el)
  }

  return hasAuth
}

export default {
  install(app) {
    app.directive('permission', {
      mounted(el, binding) {
        // el: 当前绑定的DOM对象，binding：当前的指令传入的参数
        hasPermission(binding.value, el)
      },
    })
  },
}
